package at.ac.tuwien.prog.view;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author christoph.pickl@student.tuwien.ac.at
 */
public class ReadInputDialog extends JDialog {

	private static final Log LOG = LogFactory.getLog(ReadInputDialog.class);
	
	private static final long serialVersionUID = 2878709957921236940L;

	private int result = -1;
	
	private boolean confirmed = false;
	
	private final JTextField textField = new JTextField(2);
	
	/*
	TODO input type for ascii/int
	public enum UserInputType {
		ASCII,
		INT;
	}
	 */
	
	
	public ReadInputDialog(JFrame owner, final String promptText) {
		super(owner, "Input Prompt", true);
		
		this.setResizable(false);
		this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				onCancel();
			}
		});
		
		final JButton btnEnter = new JButton("Enter");
		btnEnter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {
			onEnter();
		}});
		final JButton btnCancel = new JButton("Cancel");
		btnCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {
			onCancel();
		}});
		this.getRootPane().setDefaultButton(btnEnter);
		
		final JPanel panel = new JPanel();
		panel.add(new JLabel(promptText));
		panel.add(this.textField);
		panel.add(btnEnter);
		panel.add(btnCancel);
		
		this.add(panel);
		this.pack();
		this.setLocationRelativeTo(owner);
	}

	private void onEnter() {
		LOG.debug("onEnter() invoked");
		
		final String text = this.textField.getText();
		try {
			
			this.result = Integer.parseInt(text);
			this.confirmed = true;
			this.dispose();
			
		} catch(NumberFormatException e) {
			Toolkit.getDefaultToolkit().beep();
		}
	}
	
	private void onCancel() {
		LOG.debug("onCancel() invoked");
		this.dispose();
	}
	
	public boolean isConfirmed() {
		return this.confirmed;
	}
	
	public int getUserInput() {
		return this.result;
	}
	
}
